package com.bootdo.system.controller;

import com.blade.kit.json.JSONArray;
import com.blade.kit.json.JSONObject;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.service.MenuService;
import com.wechat.util.Constant;
import com.wechat.util.Matchers;
import com.wechat.util.MessageListener;
import com.wechat.util.WechatApiUtil;
import com.wechat.util.WechatMeta;
import com.wechat.util.WxLocalCache;

import io.swagger.models.auth.In;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MenuService menuService;
	@Autowired
	FileService fileService;
	@GetMapping({ "/", "" })
	String welcome(Model model) {

		return "redirect:/blog";
	}
	
	@RequestMapping("/wxindex")
	public ModelAndView index(ModelAndView view) {
		view.setViewName("index");
		String uuid = WechatApiUtil.getUUID();
		view.addObject("codeImg", WechatApiUtil.getQrCode(uuid));
		view.addObject("uuid", uuid);
		return view;
	}

	@RequestMapping("/wxlogin")
	@ResponseBody
	public Map<String, String> login(ModelAndView view, String uuid) throws InterruptedException {
		Map<String, String> resultMap = new HashMap();
		while (true) {

			String res = WechatApiUtil.waitLogin(0, uuid);
			String code = Matchers.match("window.code=(\\d+);", res);

			if (!Constant.HTTP_OK.equals(code)) {
				System.out.println("wait for login...");
				Thread.sleep(2000);
				continue;
			}
			WechatMeta meta = WechatApiUtil.newWechatMeta(res);
			WechatApiUtil.login(meta);
			JSONObject wxInitObj = WechatApiUtil.wxInit(meta);
			WechatApiUtil.openStatusNotify(meta);

			JSONArray contactList = wxInitObj.get("ContactList").asArray();
			WxLocalCache.init(meta).setLatestContactList(contactList);

			MessageListener listener = new MessageListener(meta);
			listener.listen();

			break;
		}

		resultMap.put("code", "0");
		resultMap.put("message", "登录成功,正在监听消息...");
		return resultMap;
	}
	
	
	

	@Log("请求访问主页")
	@GetMapping({ "/index" })
	String index(Model model) {
		List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("name", getUser().getName());
		FileDO fileDO = fileService.get(getUser().getPicId());
		if(fileDO!=null&&fileDO.getUrl()!=null){
			if(fileService.isExist(fileDO.getUrl())){
				model.addAttribute("picUrl",fileDO.getUrl());
			}else {
				model.addAttribute("picUrl","/img/photo_s.jpg");
			}
		}else {
			model.addAttribute("picUrl","/img/photo_s.jpg");
		}
		model.addAttribute("username", getUser().getUsername());
		return "index_v1";
	}

	@GetMapping("/login")
	String login() {
		return "login";
	}

	@Log("登录")
	@PostMapping("/login")
	@ResponseBody
	R ajaxLogin(String username, String password) {

		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return R.ok();
		} catch (AuthenticationException e) {
			return R.error("用户或密码错误");
		}
	}

	@GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/login";
	}

	@GetMapping("/main")
	String main() {
		return "main";
	}

}
